package webservices;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import classes.Proizvod;
import dao.DAOFactory;

@Path("/proizvodi")
public class ProizvodResource {
	@Context
	 UriInfo uriInfo;
	 @Context
	 Request request;

	 @Path("/svi")
		@GET
		@Produces(MediaType.APPLICATION_XML)
		public GenericEntity<List<Proizvod>> vratiProizvode() {
			try {
				DAOFactory.connect();
				List<Proizvod> proizvodi = DAOFactory.getProizvodDAO().selectSveProizvode();
				DAOFactory.disconnect();
				return new GenericEntity<List<Proizvod>>(proizvodi){};
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
	
	 @Path("/proizvod/{id}")
		@GET
		@Produces(MediaType.APPLICATION_XML)
		public Proizvod vratiProizvod(@PathParam("id")String sIDProizvoda) {
			try {
				int IDProizvoda = Integer.parseInt(sIDProizvoda);
				DAOFactory.connect();
				Proizvod p = DAOFactory.getProizvodDAO().selectProizvod(IDProizvoda);
				DAOFactory.disconnect();
				return p;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
	 
	 @PUT
	  @Path("proizvod/novi")
	  @Consumes(MediaType.APPLICATION_XML)
	  @Produces(MediaType.APPLICATION_XML)
	  public String putTip(@HeaderParam("username")String username, @HeaderParam("password")String password, Proizvod p) throws Exception {
		  try{
			  DAOFactory.connect();
			  DAOFactory.getProizvodDAO().insertProizvod(p);
			  DAOFactory.disconnect();
			  return Boolean.toString(true);
		  }
		  catch(Exception e){
			  e.printStackTrace();
			  return Boolean.toString(false);
		  }
	  }
	 
	 
	 @POST
	  @Path("proizvod/obrisi")
	  @Consumes(MediaType.APPLICATION_XML)
	  @Produces(MediaType.APPLICATION_XML)
	  public String deleteTipPOST(@HeaderParam("username")String username, @HeaderParam("password")String password, String sIDProizvoda){
		  try{
			  int IDProizvoda = Integer.parseInt(sIDProizvoda);
			  DAOFactory.connect();
			  int i = DAOFactory.getProizvodDAO().deleteProizvod(IDProizvoda);
			  if (i!=1){
				  DAOFactory.disconnect();
				  return Boolean.toString(false);
			  }
			  DAOFactory.disconnect();
			  return Boolean.toString(true);
		  }
		  catch(Exception e){
			  e.printStackTrace();
			  return Boolean.toString(false);
		  }
	  }

}
